package io.anywhere;

import com.sun.net.httpserver.HttpServer;
import picocli.CommandLine;
import picocli.CommandLine.ParseResult;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

public class Boot {
  public static void main(String[] args) {
    final CliOptions opt = new CliOptions();
    final CommandLine commandLine = new CommandLine(opt);
    try {
      final ParseResult parseResult = commandLine.parseArgs(args);
      if (parseResult.isUsageHelpRequested()) {
        commandLine.usage(System.out);
        System.exit(0);
      }
      if (parseResult.isVersionHelpRequested()) {
        commandLine.printVersionHelp(System.out);
        System.exit(0);
      }
      startServer(opt);
      System.out.println("Staring server: http://" + opt.server + ":" + opt.port + "/ directory:" + opt.dir);
    } catch (Exception e) {
      commandLine.usage(System.out);
      System.exit(1);
    }
  }

  public static void startServer(CliOptions opt) throws Exception {
    HttpServer server = HttpServer.create(new InetSocketAddress(opt.server, opt.port), 0);

    // 创建HttpContext，将路径为/请求映射到SimpleStaticHttpHandler处理器
    server.createContext("/", new SimpleStaticHttpHandler(opt.dir));

    // 设置服务器的线程池对象
    server.setExecutor(Executors.newFixedThreadPool(2));

    // 启动服务器
    server.start();
  }
}
